package swing;

import model.FavoritableEntity;
import model.IItem;

import javax.swing.*;
import java.awt.*;
import java.util.LinkedHashMap;
import java.util.Map;

import static java.lang.String.format;

/**
 * Created by nuno-rafael-figueiredo on 09-03-2014.
 */
public class FavoriteButton<TKey, TItem extends IItem<TKey>> extends JButton {
    private static final Map<Boolean, Icon> icons = new LinkedHashMap<>();

    private boolean favorite;
    private final FavoritableEntity<TKey, TItem> entity;
    private final TItem item;

    public FavoriteButton(FavoritableEntity<TKey, TItem> entity, TItem item) {
        this.entity = entity;
        this.item = item;
        setFavorite(entity.isFavorite(item), false);

        addActionListener(actionEvent -> setFavorite(!favorite, true));
    }

    public void setFavorite(boolean favorite, boolean set) {
        this.favorite = favorite;
        if (set)
            entity.setFavorite(item, favorite);

        setIcon(fetchIcon(favorite));
    }

    private static Icon fetchIcon(boolean favorite) {
        if (!icons.containsKey(favorite)) {
            String path = format("icons/%s_24x24.png", favorite ? "favorite" : "non-favorite");
            Image image = Images.loadImage(Favorite.class, path);
            Icon icon = new ImageIcon(image);
            icons.put(favorite, icon);
        }

        return icons.get(favorite);
    }
}
